package run.halo.app.task;

import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import run.halo.app.model.entity.Photo;
import run.halo.app.model.entity.Post;
import run.halo.app.service.PhotoService;
import run.halo.app.service.PostService;

/**
 * @author Wh1te
 * @author guqing
 * @date 2020-10-19
 */
@Slf4j
@Component
public class PhotoRandomTask {

    private final PhotoService photoService;

    private final PostService postService;

    public PhotoRandomTask(PhotoService photoService, PostService postService) {
        this.photoService = photoService;
        this.postService = postService;
    }

    /**
     * 图片随机任务：用于变更文章背景图
     * 0/20 * * * * ?
     */
    @Scheduled(cron = "0 0 */1 * * ?")
    public synchronized void run() {

        log.info("Start change the photos of posts task");
        List<Photo> photos = photoService.listAll();

        if (CollectionUtils.isEmpty(photos)){
            return;
        }

        List<Post> posts = postService.listAll();

        if (CollectionUtils.isEmpty(posts)){
            return;
        }

        for (Post post : posts) {
            int nextInt = RandomUtils.nextInt(0, photos.size());
            post.setThumbnail(photos.get(nextInt).getUrl());
            postService.update(post);
        }

        log.info("The change the photos of posts task is end");
    }

}
